package com.test.schoolhelper.ui.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.test.schoolhelper.R;

import java.io.File;

// TODO: 2024/5/29 播放音乐的服务 
public class MusicService extends Service {

    public MediaPlayer player;
    private boolean destroy;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new Finder();
    }

    public class Finder extends Binder{

        public int getDuration() {
            try {
                if (destroy) {
                    return 0;
                }
                return player.getDuration();
            }catch (IllegalStateException e){
                e.printStackTrace();
            }
            return 0;
        }

        public int getCurrentPosition() {
            try {
                if (destroy) {
                    return 0;
                }
                return player.getCurrentPosition();
            }catch (IllegalStateException e){
                e.printStackTrace();
            }
            return 0;
        }

        public void setProgress(int s) {
            player.seekTo(s);
        }

    }

    public void onCreate() {
        super.onCreate();
       // player = MediaPlayer.create(this, R.raw.music);
        File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + "music.mp3");// 创建一个文件对象
        player=MediaPlayer.create(this, Uri.fromFile(file));
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        switch (intent.getIntExtra("play", -1)) {
            case 1:
                player.start();
                break;
            case 2:
                if (player != null && player.isPlaying()) {
                    player.pause();
                } else {
                    player.start();
                }
                break;
        }

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        destroy=true;
        player.release();
        player=null;
    }
}